﻿using System.Net;
using System.Text;
using Klear.Library.Helpers;
using Newtonsoft.Json.Linq;

namespace Klear.Library.Services;

public class NewsService
{
    public async Task<string> GetFirstNews()
    {
        string res="加载失败";
        using (HttpClient client = new HttpClient())
        {
            HttpContent content = new StringContent(AccessKeyStorage.NEWS_BODY, Encoding.UTF8, "application/x-www-form-urlencoded");
            try
            {
                HttpResponseMessage response = await client.PostAsync(AccessKeyStorage.NEWS_URL, content);
                response.EnsureSuccessStatusCode();

                res = await response.Content.ReadAsStringAsync();
                JObject responseMsg = JObject.Parse(res);
                string innerJsonText = responseMsg["result"]?["list"][0]?.ToString();
                if (string.IsNullOrEmpty(innerJsonText))
                {
                    throw new Exception("Inner JSON text is null or empty.");
                }
                JObject innerJson = JObject.Parse(innerJsonText);
                res = innerJson["title"]?.ToString() ?? "加载失败"; 
                
                
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred: " + ex.Message);
            }
            return res;
        }
    }
    
}